package com.yc.c118s3plyqnzf.controller;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    // 存根函数

    // 返回值表示继续下一个拦截器的执行，如果没有则访问目标资源
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // Servlet => Filter.doFilter(请求，响应，FilterChain=> 过滤器链对象){
        // FilterChain.doFilter(请求，响应)
        //}
        // pre ==> 前置 ==> 前置拦截
        if (request.getSession().getAttribute("loginedUser") == null){
            response.sendRedirect("/login.html");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("========postHandle============");
        // post ==> 后置拦截
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 最终拦截 ==> finally
        System.out.println("========afterCompletion============");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
